<template>
  <div ref="cesiumContainer" class="cesium-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as Cesium from 'cesium'
import { createMouseEventHandler } from '../utils/MouseEvent.js'
import { cesiumMapStore } from '../stores/cesiumMap.js'

// Props
const props = defineProps({
  mapboxToken: {
    type: String,
    required: true
  }
})

// Store
const mapStore = cesiumMapStore()

// Refs
const cesiumContainer = ref(null)

// Variables
let viewer = null
let mouseEventHandler = null

// Cesium Ion Token
const cesiumIonToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhODg2OTQyOC03YWNiLTRkNGMtYWMxMi1mYjcwMTViOTBiZDkiLCJpZCI6MTk0NzksInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NzU1OTgyMjN9.It5qL2PBTwwsumH_PTrqFdFwkRaNPsHJtWJOeEcVQXE'

// 初始化地球
const initializeCesium = () => {
  try {
    // 设置 Cesium Ion Token
    if (cesiumIonToken) {
      Cesium.Ion.defaultAccessToken = cesiumIonToken
    }

    // 创建 Viewer
    viewer = new Cesium.Viewer(cesiumContainer.value, {
      animation: false,
      baseLayerPicker: true,
      fullscreenButton: true,
      geocoder: true,
      homeButton: true,
      infoBox: true,
      sceneModePicker: true,
      selectionIndicator: true,
      timeline: false,
      navigationHelpButton: false,
      scene3DOnly: false,
      terrainProvider: undefined,
      orderIndependentTranslucency: false,
      contextOptions: {
        webgl: {
          alpha: false,
          antialias: true,
          preserveDrawingBuffer: true,
          powerPreference: "high-performance"
        }
      },
      useBrowserRecommendedResolution: false,
      resolutionScale: window.devicePixelRatio || 1
    })

    // 设置初始视角
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 5000000), // 北京上空
      orientation: {
        heading: 0.0,
        pitch: -Cesium.Math.PI_OVER_TWO,
        roll: 0.0
      }
    })

    // 隐藏Cesium信用信息
    viewer.cesiumWidget.creditContainer.style.display = 'none'

    // 创建鼠标事件处理器
    mouseEventHandler = createMouseEventHandler(viewer)

    // 添加鼠标事件监听器
    if (mouseEventHandler) {
      // 鼠标左键按下事件
      mouseEventHandler.addEventListener('leftDown', (eventData) => {
        console.log('鼠标左键按下:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标左键弹起事件
      mouseEventHandler.addEventListener('leftUp', (eventData) => {
        console.log('鼠标左键弹起:', eventData)
        updateMouseStatusToStore(eventData)

        // 输出详细的数据信息
        outputDetailedInfo(eventData)
      })

      // 鼠标左键拖拽事件
      mouseEventHandler.addEventListener('leftDrag', (eventData) => {
        // console.log('鼠标左键拖拽:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标中键按下事件
      mouseEventHandler.addEventListener('middleDown', (eventData) => {
        console.log('鼠标中键按下:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标中键弹起事件
      mouseEventHandler.addEventListener('middleUp', (eventData) => {
        console.log('鼠标中键弹起:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标中键拖拽事件
      mouseEventHandler.addEventListener('middleDrag', (eventData) => {
        console.log('鼠标中键拖拽:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标滚轮事件
      mouseEventHandler.addEventListener('wheel', (eventData) => {
        console.log('鼠标滚轮:', eventData)
        updateMouseStatusToStore(eventData)
      })

      // 鼠标移动事件（防抖处理）
      mouseEventHandler.addEventListener('mouseMove', (eventData) => {
        updateMouseStatusToStore(eventData, true)
      })
    }

    console.log('Cesium初始化完成，鼠标事件监听已启用')

    // 初始化store中的地图状态
    const initialMapLevel = calculateZoomLevel(viewer.camera.positionCartographic.height)
    mapStore.setMapLevel(initialMapLevel)

    // 初始化屏幕中心位置
    const cesiumCanvas = viewer.scene.canvas
    const centerX = cesiumCanvas.clientWidth / 2
    const centerY = cesiumCanvas.clientHeight / 2
    mapStore.setScreenPosition(centerX, centerY)

  } catch (error) {
    console.error('Cesium初始化失败:', error)
  }
}

// 根据相机高度计算瓦片层级
const calculateZoomLevel = (height) => {
  if (height > 20000000) return 2
  if (height > 10000000) return 3
  if (height > 5000000) return 4
  if (height > 2500000) return 5
  if (height > 1250000) return 6
  if (height > 600000) return 7
  if (height > 300000) return 8
  if (height > 150000) return 9
  if (height > 75000) return 10
  if (height > 35000) return 11
  if (height > 15000) return 12
  return 13
}

// 更新鼠标状态到store
const updateMouseStatusToStore = (eventData, isMouseMove = false) => {
  try {
    // 更新基础鼠标状态
    mapStore.updateMouseStatus({
      position: eventData.position,
      pickedObject: eventData.pickedObject,
      cartesian: eventData.cartesian,
      cartographic: eventData.cartographic,
      wheelDelta: eventData.wheelDelta || 0
    })

    // 更新屏幕位置
    if (eventData.position) {
      mapStore.setScreenPosition(eventData.position.x, eventData.position.y)
    }

    // 更新地图层级
    if (viewer && viewer.camera) {
      const height = viewer.camera.positionCartographic.height
      const zoomLevel = calculateZoomLevel(height)
      mapStore.setMapLevel(zoomLevel)
    }

  } catch (error) {
    console.error('更新鼠标状态失败:', error)
  }
}

// 输出详细数据信息
const outputDetailedInfo = (eventData) => {
  try {
    console.log('=== 详细数据信息 ===')

    // 1. 瓦片数据
    const tileData = getTileData()
    console.log('瓦片数据:', tileData)

    // 2. 瓦片POI数据  
    const tilePOIData = getTilePOIData()
    console.log('瓦片POI数据:', tilePOIData)

    // 3. 视口内POI数据
    const viewportPOIData = getViewportPOIData()
    console.log('视口内POI数据:', viewportPOIData)

    // 4. 视口内避让后POI数据
    const collisionAvoidedPOIData = getCollisionAvoidedPOIData()
    console.log('视口内避让后POI数据:', collisionAvoidedPOIData)

    // 5. 屏幕垂直位置
    const screenVerticalPosition = getScreenVerticalPosition(eventData)
    console.log('屏幕垂直位置:', screenVerticalPosition)

    // 6. 地图层级
    const mapLevel = getCurrentMapLevel()
    console.log('地图层级:', mapLevel)

    // 7. 鼠标状态
    const mouseStatus = getMouseStatus(eventData)
    console.log('鼠标状态:', mouseStatus)

    console.log('=== 数据输出完成 ===')

  } catch (error) {
    console.error('输出详细信息失败:', error)
  }
}

// 获取瓦片数据
const getTileData = () => {
  if (!viewer) return null

  const camera = viewer.camera
  const cartographic = camera.positionCartographic
  const height = cartographic.height
  const zoomLevel = calculateZoomLevel(height)

  return {
    currentZoomLevel: zoomLevel,
    cameraHeight: height,
    cameraLongitude: Cesium.Math.toDegrees(cartographic.longitude),
    cameraLatitude: Cesium.Math.toDegrees(cartographic.latitude),
    viewportBounds: getViewportBounds(),
    tileCount: getTileCount(zoomLevel)
  }
}

// 获取瓦片POI数据
const getTilePOIData = () => {
  // 模拟瓦片POI数据，实际项目中应该从数据源获取
  return {
    totalPOICount: 0,
    loadedTiles: 0,
    poiByCategory: {},
    loadingStatus: '无POI数据加载'
  }
}

// 获取视口内POI数据
const getViewportPOIData = () => {
  if (!viewer) return null

  const viewportBounds = getViewportBounds()

  return {
    viewportBounds: viewportBounds,
    visiblePOICount: 0,
    poiInViewport: [],
    viewportArea: calculateViewportArea(viewportBounds)
  }
}

// 获取视口内避让后POI数据
const getCollisionAvoidedPOIData = () => {
  return {
    originalPOICount: 0,
    collisionAvoidedCount: 0,
    displayedPOICount: 0,
    collisionAvoidanceRate: 0,
    avoidanceAlgorithm: '无避让算法'
  }
}

// 获取屏幕垂直位置
const getScreenVerticalPosition = (eventData) => {
  if (!eventData.position || !viewer) return null

  const canvas = viewer.scene.canvas
  const screenHeight = canvas.clientHeight
  const mouseY = eventData.position.y

  return {
    mouseY: mouseY,
    screenHeight: screenHeight,
    verticalPercentage: ((screenHeight - mouseY) / screenHeight * 100).toFixed(2) + '%',
    relativePosition: mouseY < screenHeight * 0.33 ? '上部' :
      mouseY < screenHeight * 0.67 ? '中部' : '下部'
  }
}

// 获取当前地图层级
const getCurrentMapLevel = () => {
  if (!viewer) return null

  const height = viewer.camera.positionCartographic.height
  const zoomLevel = calculateZoomLevel(height)

  return {
    zoomLevel: zoomLevel,
    cameraHeight: height,
    heightRange: getHeightRange(zoomLevel),
    description: getZoomLevelDescription(zoomLevel)
  }
}

// 获取鼠标状态
const getMouseStatus = (eventData) => {
  const mouseState = mouseEventHandler ? mouseEventHandler.getMouseState() : null

  return {
    eventType: 'leftUp',
    position: eventData.position,
    screenCoordinates: eventData.position ?
      `(${eventData.position.x}, ${eventData.position.y})` : null,
    worldCoordinates: eventData.cartesian,
    geographicCoordinates: eventData.cartographic ? {
      longitude: Cesium.Math.toDegrees(eventData.cartographic.longitude),
      latitude: Cesium.Math.toDegrees(eventData.cartographic.latitude),
      height: eventData.cartographic.height
    } : null,
    pickedObject: eventData.pickedObject,
    mouseState: mouseState,
    timestamp: new Date().toISOString()
  }
}

// 获取视口边界
const getViewportBounds = () => {
  if (!viewer) return null

  const canvas = viewer.scene.canvas
  const rectangle = viewer.camera.computeViewRectangle()

  if (!rectangle) return null

  return {
    west: Cesium.Math.toDegrees(rectangle.west),
    south: Cesium.Math.toDegrees(rectangle.south),
    east: Cesium.Math.toDegrees(rectangle.east),
    north: Cesium.Math.toDegrees(rectangle.north),
    width: canvas.clientWidth,
    height: canvas.clientHeight
  }
}

// 获取瓦片数量估算
const getTileCount = (zoomLevel) => {
  // 根据缩放级别估算可见瓦片数量
  const baseTileCount = 4 // 基础瓦片数
  return Math.pow(4, Math.max(0, zoomLevel - 1))
}

// 计算视口面积
const calculateViewportArea = (bounds) => {
  if (!bounds) return 0

  const width = bounds.east - bounds.west
  const height = bounds.north - bounds.south
  return Math.abs(width * height)
}

// 获取高度范围
const getHeightRange = (zoomLevel) => {
  const ranges = {
    2: '> 20,000,000m',
    3: '10,000,000m - 20,000,000m',
    4: '5,000,000m - 10,000,000m',
    5: '2,500,000m - 5,000,000m',
    6: '1,250,000m - 2,500,000m',
    7: '600,000m - 1,250,000m',
    8: '300,000m - 600,000m',
    9: '150,000m - 300,000m',
    10: '75,000m - 150,000m',
    11: '35,000m - 75,000m',
    12: '15,000m - 35,000m',
    13: '< 15,000m'
  }
  return ranges[zoomLevel] || '未知范围'
}

// 获取缩放级别描述
const getZoomLevelDescription = (zoomLevel) => {
  const descriptions = {
    2: '全球视图',
    3: '大洲视图',
    4: '国家视图',
    5: '大区域视图',
    6: '区域视图',
    7: '省份视图',
    8: '城市视图',
    9: '市区视图',
    10: '街区视图',
    11: '街道视图',
    12: '建筑视图',
    13: '详细视图'
  }
  return descriptions[zoomLevel] || '未知级别'
}

onMounted(() => {
  initializeCesium()
})

onUnmounted(() => {
  // 清理鼠标事件处理器
  if (mouseEventHandler) {
    mouseEventHandler.destroy()
    mouseEventHandler = null
  }

  // 清理viewer
  if (viewer) {
    viewer.destroy()
    viewer = null
  }
})
</script>

<style scoped>
.cesium-container {
  width: 100%;
  height: 100%;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-smooth: always;
}

/* 隐藏Cesium的版权信息 */
.cesium-container :deep(.cesium-credit-container) {
  display: none !important;
}

/* 优化Cesium画布渲染 */
.cesium-container :deep(.cesium-widget canvas) {
  image-rendering: auto !important;
  image-rendering: -webkit-optimize-contrast !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
}

/* 调整Cesium工具栏样式 */
.cesium-container :deep(.cesium-viewer-toolbar) {
  background: rgba(42, 42, 42, 0.8);
  border-radius: 6px;
}

.cesium-container :deep(.cesium-button) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.cesium-container :deep(.cesium-button:hover) {
  background: rgba(255, 255, 255, 0.2);
}
</style>